﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Bson;
using MongoDB.Driver;
using System.Data;
using System.Net;
using System.IO;
using System.Collections.Specialized;
using System.Collections;
using System.Reflection;
using Web.Common;
using System.Text.RegularExpressions;
using System.Threading;
using System.Net.Mail;

namespace Client
{
    public class xx
    {

        public xx()
        {
            Console.WriteLine("xx");
        }
    }

    public static class send
    {
        #region 发送邮件的方法

        static string emailaddress = "";
        static string mailcontent = "";
        static string mailsubject = "";
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="emailaddress">邮件接收者地址</param>
        /// <param name="mailcontent">邮件主体内容</param>
        /// <param name="mailsubject">邮件主题</param>
        /// <returns>错误信息</returns>
        public static string SendMail(string tmpemailaddress, string tmpmailcontent, string tmpmailsubject)
        {

            emailaddress = tmpemailaddress;
            mailcontent = tmpmailcontent;
            mailsubject = tmpmailsubject;
            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
            return "";

        }
        /// <summary>
        /// 构建异步调用方法
        /// </summary>
        /// <param name="o"></param>
        public static string ThreadProc(string tmpemailaddress, string tmpmailcontent, string tmpmailsubject)
        {
            emailaddress = tmpemailaddress;
            mailcontent = tmpmailcontent;
            mailsubject = tmpmailsubject;
            string Mailuser = "admin@soujb.com";
            string EmailPwd = "wang1234";
            string Loginuser = "admin@soujb.com";
            string EmailHost = "smtp.soujb.com";
            MailMessage objMailMessage = new MailMessage();

            objMailMessage.From = new MailAddress(Mailuser, "豆豆淘", System.Text.Encoding.UTF8);
            objMailMessage.To.Add(new MailAddress(emailaddress));
            objMailMessage.BodyEncoding = System.Text.Encoding.UTF8;
            objMailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
            objMailMessage.Subject = mailsubject;
            objMailMessage.Body = mailcontent;
            objMailMessage.IsBodyHtml = true;
            SmtpClient objSmtpClient = new SmtpClient(EmailHost);
            objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            objSmtpClient.Credentials = new System.Net.NetworkCredential(Loginuser, EmailPwd);
            try
            {
                objSmtpClient.Send(objMailMessage);
                return "ok";
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }
        /// <summary>
        /// 构建异步调用方法
        /// </summary>
        /// <param name="o"></param>
        static void ThreadProc(object o)
        {
            string Mailuser = "administrator";
            string EmailPwd = "qw12!@";
            string Loginuser = "administrator";
            string EmailHost = "smtp.soujb.com";
            MailMessage objMailMessage = new MailMessage();

            objMailMessage.From = new MailAddress(Mailuser, "豆豆淘", System.Text.Encoding.UTF8);
            objMailMessage.To.Add(new MailAddress(emailaddress));
            objMailMessage.BodyEncoding = System.Text.Encoding.UTF8;
            objMailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
            objMailMessage.Subject = mailsubject;
            objMailMessage.Body = mailcontent;
            objMailMessage.IsBodyHtml = true;
            SmtpClient objSmtpClient = new SmtpClient(EmailHost);
            objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            objSmtpClient.Credentials = new System.Net.NetworkCredential(Loginuser, EmailPwd);
            try
            {
                objSmtpClient.Send(objMailMessage);
            }
            catch (Exception ex)
            {

            }
        }
        #endregion
    }
    class Program : xx
    {
        Program()
        {
            Console.WriteLine("Program");
        }
        static void Main(string[] args)
        {
            
            //string sql = "select ProMoteMessge,GuaranteeMessage from ProDataBasic where Id=10452";

            //DataTable dt = DbHelperSQL.ExecuteSelect(sql).Tables[0];

            //Console.WriteLine(DateTime.Now.ToString()+"--"+DateTime.Now.Millisecond);
            //Console.WriteLine(dt.Rows[0][1]);

            //Console.WriteLine(Regex.IsMatch("4000000000002.00", @"^([0-9]|[1-9][0-9]+)(\.[0-9]{0,2})?$"));
            for (int i = 0; i < 1; i++)
            {
                Console.WriteLine(send.ThreadProc("dongxiaojie@doudoutao.com", "你可以打开窗户看看", "今天天气很好的"));
            }
           
            #region
            /*
            //string postString = "emailName=a&passWord=b";//这里即为传递的参数，可以用工具抓包分析，也可以自己分析，主要是form里面每一个name都要加进来  
            //string url = "http://wcfservice.doudoutao.com/UserRegister.svc/web/UserLogin";
            string url = "http://wcfservice.doudoutao.com/Index.svc/web/ProSearch";
            //string url = "http://192.168.0.196:80/Index.svc";
            //string url = "http://www.www.doudoutao.com";
            string postString = "{\"keyWord\":\"只\",\"pageSize\":5,\"pageIndex\":1}";
            //string postString = "{\"productid\":\"10452\"}";
            //string postString = "productid=10452";
            //string postString = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body><GetProPics xmlns=\"http://tempuri.org/\"><productid>10452</productid></GetProPics></s:Body></s:Envelope>";
            //postString = "emailName=a&passWord=b";
            byte[] postData = Encoding.UTF8.GetBytes(postString);//编码，尤其是汉字，事先要看下抓取网页的编码方式  
            WebClient webClient = new WebClient();
            webClient.Headers.Add("Content-Type", "application/json");//采取POST方式必须加的header，如果改为GET方式的话就去掉这句话即可 
            //webClient.Headers.Add("Content-Type", "text/xml;charset=utf-8");//采取POST方式必须加的header，如果改为GET方式的话就去掉这句话即可  text/xml;
           //webClient.Headers.Add("SOAPAction", "\"http://tempuri.org/IMobileProduct/GetProPics\"");
            //webClient.Headers.Add("Host", "wcfservice.doudoutao.com");
            //webClient.Headers.Add("Accept-Encoding", "gzip, deflate");
            byte[] responseData = webClient.UploadData(url, "POST", postData);//得到返回字符流  
            string srcString = Encoding.UTF8.GetString(responseData);//解码  

            Console.WriteLine(srcString);
            */
            
            #endregion
            #region
            /*string attrwhere = "";
            int[] attrs =new int[]{};
            for (int i = 0; i < attrs.Length; i++)
            {
                if (i == 0)
                {
                    attrwhere += " Type_Attr_Val_Id in (";
                }
                attrwhere += attrs[i] + ",";
                if (i == attrs.Length - 1)
                {
                    attrwhere=attrwhere.Substring(0, attrwhere.Length - 1);
                    attrwhere += ")";
                }

            }
            Console.WriteLine(attrwhere);*/
            #endregion
            #region
            //#region
            //ServiceReference1.ServiceClient proxy = new ServiceReference1.ServiceClient();
            ////string str = proxy.setMsg("欢迎来到WCF村！");
            ////Console.WriteLine(str);

            ////Data d = proxy.getData();
            ////Console.WriteLine("Name:{0} ;Age:{1} ; MSG: {2}", d.Name, d.age, d.msg);


            //Data data = new Data();
            ////data.Name = "Mush Service";
            ////data.age = 20;
            //data = proxy.setData(data);
            //Console.WriteLine("Name:{0} ;Age:{1} ; MSG: {2}", data.Name, data.age, data.msg);
            ////Console.WriteLine(proxy.DoWork());
            //Console.ReadLine();
            //#endregion

            /*
            #region
            ////连接信息
            //string conn = "mongodb://root:123456@192.168.0.196:27017";
            //string database = "mvc";
            //string collection = "student";

            //MongoServer mongodb = MongoServer.Create(conn);//连接数据库
            //MongoDatabase mongoDataBase = mongodb.GetDatabase(database);//选择数据库名
            //MongoCollection mongoCollection = mongoDataBase.GetCollection(collection);//选择集合，相当于表

            //mongodb.Connect();

            ////普通插入
            ////var o = new { Uid = 123, Name = "root", PassWord = "111111" };
            ////mongoCollection.Insert(o);

            //////对象插入
            ////Person p = new Person { Uid = 124, Nam,e = "xixiObject", PassWord = "222222" };
            ////mongoCollection.Insert(p);

            //////BsonDocument 插入
            ////BsonDocument b = new BsonDocument();
            ////b.Add("Uid", 125);
            ////b.Add("Name", "xixiBson");
            ////b.Add("PassWord", "333333");
            ////mongoCollection.Insert(b);
            ////mongoCollection.RemoveAll();
            ////long c = mongoCollection.Count();
            ////if (true)
            ////{
            ////    for (long i = 1; i <= 500000; i++)
            ////    {
            ////        Insert(mongoCollection, i);
            ////    }


            ////}
            
            ////Console.WriteLine("数据条数:{0}", c);
            //QueryDocument query = new QueryDocument();
            //BsonDocument b = new BsonDocument();
            //b.Add("$gt", 5500);
            //b.Add("$lt", 5510);
            //query.Add("key", b);
            //Console.WriteLine("{0}", mongoCollection.Count());

            //Console.WriteLine("查询开始时间:{0}", DateTime.Now + ":" + DateTime.Now.Millisecond);
            //MongoCursor<BsonDocument> p = mongoCollection.FindAs<BsonDocument>(query);
            //Console.WriteLine("查询结束时间:{0}", DateTime.Now + ":" + DateTime.Now.Millisecond);
            //long pcount = p.Count();
            //Console.WriteLine("------------------------{0}",pcount);
            //StringBuilder sb = new StringBuilder();
            //Console.WriteLine("遍历开始时间:{0}", DateTime.Now + ":" + DateTime.Now.Millisecond);
            //foreach (BsonDocument emp in p)
            //{
            //    // BsonValue有两种取值方式，下面两个都用了一个是AsXXX,一个是ToXXX
            //    sb.AppendFormat("key:{0} addtime:{1} number:{2} value:{3}{4} ", emp["key"].ToString(), ((DateTime)emp["addtime"].AsBsonDateTime).ToString("yyyy-MM-dd"), emp["number"].ToString(), emp["value"].AsGuid, "\n");
            //}
            //Console.WriteLine(sb.ToString());
            //Console.WriteLine("遍历结束时间:{0}", DateTime.Now + ":" + DateTime.Now.Millisecond);
            //Console.ReadLine();
            #endregion

            */
            #endregion
        }
        #region 
        static Random ss = new Random();
        /// <summary>
        /// 插入数据
        /// </summary>
        static void Insert(MongoCollection collection, long id)
        {
            // -------------------------------------------------------------------------           
            // 创建一个employee
            BsonDocument employee = new BsonDocument
            {
              { "key",id  },
              { "value", Guid.NewGuid()},
              {"addtime",DateTime.Now.AddMinutes(id)},
              {"number",ss.Next(1,100)}
            };
            // 把它写到上面那个集合里面去
            collection.Insert(employee);
        }

        private static string HttpPostData(string url, int timeOut, string fileKeyName,
                                    string filePath, NameValueCollection stringDict)
        {
            string responseContent;
            var memStream = new MemoryStream();
            var webRequest = (HttpWebRequest)WebRequest.Create(url);
            // 边界符
            var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
            // 边界符
            var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
            var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            // 最后的结束符
            var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");

            // 设置属性
            webRequest.Method = "POST";
            webRequest.Timeout = timeOut;
            webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

            // 写入文件
            const string filePartHeader =
                "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
                 "Content-Type: application/octet-stream\r\n\r\n";
            var header = string.Format(filePartHeader, fileKeyName, filePath);
            var headerbytes = Encoding.UTF8.GetBytes(header);

            memStream.Write(beginBoundary, 0, beginBoundary.Length);
            memStream.Write(headerbytes, 0, headerbytes.Length);

            var buffer = new byte[1024];
            int bytesRead; // =0

            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                memStream.Write(buffer, 0, bytesRead);
            }

            // 写入字符串的Key
            var stringKeyHeader = "\r\n--" + boundary +
                                   "\r\nContent-Disposition: form-data; name=\"{0}\"" +
                                   "\r\n\r\n{1}\r\n";

            foreach (byte[] formitembytes in from string key in stringDict.Keys
                                             select string.Format(stringKeyHeader, key, stringDict[key])
                                                 into formitem
                                                 select Encoding.UTF8.GetBytes(formitem))
            {
                memStream.Write(formitembytes, 0, formitembytes.Length);
            }

            // 写入最后的结束边界符
            memStream.Write(endBoundary, 0, endBoundary.Length);

            webRequest.ContentLength = memStream.Length;

            var requestStream = webRequest.GetRequestStream();

            memStream.Position = 0;
            var tempBuffer = new byte[memStream.Length];
            memStream.Read(tempBuffer, 0, tempBuffer.Length);
            memStream.Close();

            requestStream.Write(tempBuffer, 0, tempBuffer.Length);
            requestStream.Close();

            var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();

            using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(),
                                                            Encoding.GetEncoding("utf-8")))
            {
                responseContent = httpStreamReader.ReadToEnd();
            }

            fileStream.Close();
            httpWebResponse.Close();
            webRequest.Abort();

            return responseContent;
        }

        #endregion
    }

    class ConvertHelper<T> where T : new()
    {
        /// <summary>  
        /// 利用反射和泛型  
        /// </summary>  
        /// <param name="dt">表元素</param>  
        /// <returns></returns>  
        public static List<T> ConvertToList(DataTable dt)
        {

            // 定义集合  
            List<T> ts = new List<T>();

            // 获得此模型的类型  
            Type type = typeof(T);
            //定义一个临时变量  
            string tempName = string.Empty;
            //遍历DataTable中所有的数据行  
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                // 获得此模型的公共属性  
                PropertyInfo[] propertys = t.GetType().GetProperties();
                //遍历该对象的所有属性  
                foreach (PropertyInfo pi in propertys)
                {
                    tempName = pi.Name;//将属性名称赋值给临时变量  
                    //检查DataTable是否包含此列（列名==对象的属性名）    
                    if (dt.Columns.Contains(tempName))
                    {
                        // 判断此属性是否有Setter  
                        if (!pi.CanWrite) continue;//该属性不可写，直接跳出  
                        //取值  
                        object value = dr[tempName];
                        //如果非空，则赋给对象的属性  
                        if (value != DBNull.Value)
                            pi.SetValue(t, value, null);
                    }
                }
                //对象添加到泛型集合中  
                ts.Add(t);
            }

            return ts;

        }

        /// <summary>  
        /// 利用反射和泛型  
        /// </summary>  
        /// <param name="dt"></param>  
        /// <returns></returns>  
        public static T ConvertToModel(DataRow dr)
        {

            // 获得此模型的类型  
            Type type = typeof(T);
            //定义一个临时变量  
            string tempName = string.Empty;
            //遍历DataTable中所有的数据行  
            T t = new T();
            // 获得此模型的公共属性  
            PropertyInfo[] propertys = t.GetType().GetProperties();
            //遍历该对象的所有属性  
            foreach (PropertyInfo pi in propertys)
            {
                tempName = pi.Name;//将属性名称赋值给临时变量  
                //检查DataTable是否包含此列（列名==对象的属性名）    
                if (dr.Table.Columns.Contains(tempName))
                {
                    // 判断此属性是否有Setter  
                    if (!pi.CanWrite) continue;//该属性不可写，直接跳出  
                    //取值  
                    object value = dr[tempName];
                    //如果非空，则赋给对象的属性  
                    if (value != DBNull.Value)
                        pi.SetValue(t, value, null);
                }
            }
            //对象添加到泛型集合中
            return t;

        }
    }
    public class test
    {
        public int _id { get; set; }
        public string key { get; set; }
        public string value { get; set; }
        public int number { get; set; }

    }

    /// <summary>
    /// 会员登记表
    /// </summary>
    public class UserRegister_Model
    {
        /// <summary>
        /// //标识列
        /// </summary>
        public int R_Id { get; set; }
        /// <summary>
        /// //User_Base表外键
        /// </summary>
        public int D_Id { get; set; }
        /// <summary>
        /// //姓名
        /// </summary>
        public string R_Name { get; set; }
        /// <summary>
        /// //性别
        /// </summary>
        public int R_Sex { get; set; }
        /// <summary>
        /// //出生日期
        /// </summary>
        public DateTime R_Birthday { get; set; }
        /// <summary>
        /// //日期类型 公历/阴历
        /// </summary>
        public int R_BirthdayType { get; set; }
        /// <summary>
        /// //学校
        /// </summary>
        public string R_School { get; set; }
        /// <summary>
        /// //年级
        /// </summary>
        public int R_Grade { get; set; }
        /// <summary>
        /// //班级
        /// </summary>
        public int R_Class { get; set; }
        /// <summary>
        /// //家庭地址
        /// </summary>
        public string R_Address { get; set; }
        /// <summary>
        /// //家庭电话
        /// </summary>
        public string R_Telephone { get; set; }
        /// <summary>
        /// //特长爱好
        /// </summary>
        public string R_Hobby { get; set; }
        /// <summary>
        /// //最想参加的活动
        /// </summary>
        public string R_LKActive { get; set; }
        /// <summary>
        /// //爸爸的名字
        /// </summary>
        public string R_FatherName { get; set; }
        /// <summary>
        /// //妈妈的名字
        /// </summary>
        public string R_MatherName { get; set; }
        /// <summary>
        /// //爸爸的手机
        /// </summary>
        public string R_FatherMB { get; set; }
        /// <summary>
        /// //妈妈的手机
        /// </summary>
        public string R_MatherMB { get; set; }
        /// <summary>
        /// //其他监护人姓名
        /// </summary>
        public string R_OtherGName { get; set; }
        /// <summary>
        /// //与监护人的关系
        /// </summary>
        public string R_OtherGRel { get; set; }
        /// <summary>
        /// //其他监护人手机
        /// </summary>
        public string R_OtherGMB { get; set; }
        /// <summary>
        /// //会员护照领取方式
        /// </summary>
        public int R_ReceiveWay { get; set; }
        /// <summary>
        /// 会员证编号
        /// </summary>
        public long R_Number { get; set; }
        /// <summary>
        /// 是否激活
        /// </summary>
        public int R_Activation { get; set; }
        /// <summary>
        /// 录入方式0用户 1管理员 2合并侯的资料
        /// </summary>
        public int R_InputMode { get; set; }
        /// <summary>
        /// 家庭住址省
        /// </summary>
        public int R_UProvince { get; set; }
        /// <summary>
        /// 家庭住址市
        /// </summary>
        public int R_UCity { get; set; }
        /// <summary>
        /// 家庭住址区/县
        /// </summary>
        public int R_UDistrict { get; set; }
        /// <summary>
        /// 学校地址省
        /// </summary>
        public int R_SProvince { get; set; }
        /// <summary>
        /// 学校地址市
        /// </summary>
        public int R_SCity { get; set; }
        /// <summary>
        /// 学校地址区/县
        /// </summary>
        public int R_SDistrict { get; set; }

        /// <summary>
        /// 入会时间
        /// </summary>
        public DateTime R_Join_Time { get; set; }

        /// <summary>
        /// 过期时间
        /// </summary>
        public DateTime R_Expired_Time { get; set; }
    }
}
